<script>
  import { onMount } from 'svelte';

  export let text = '';
  export let speed = 100; // 打字速度 (毫秒)
  export let delay = 0; // 开始延迟 (毫秒)
  export let cursor = true; // 是否显示光标
  export let cursorChar = '|'; // 光标字符
  export let loop = false; // 是否循环
  export let pauseTime = 2000; // 循环暂停时间

  let displayText = '';
  let currentIndex = 0;
  let showCursor = cursor;
  let isTyping = false;
  let timeoutId;

  // 响应 text 变化
  $: if (text) {
    resetAndRestart();
  }

  function typeText() {
    if (currentIndex < text.length) {
      displayText += text[currentIndex];
      currentIndex++;
      timeoutId = setTimeout(typeText, speed);
    } else {
      isTyping = false;
      if (loop) {
        timeoutId = setTimeout(() => {
          resetAndRestart();
        }, pauseTime);
      }
    }
  }

  function resetAndRestart() {
    if (timeoutId) {
      clearTimeout(timeoutId);
    }
    displayText = '';
    currentIndex = 0;
    if (text) {
      isTyping = true;
      timeoutId = setTimeout(typeText, delay);
    }
  }

  onMount(() => {
    if (text) {
      timeoutId = setTimeout(() => {
        isTyping = true;
        typeText();
      }, delay);
    }

    // 光标闪烁效果
    if (cursor) {
      const cursorInterval = setInterval(() => {
        showCursor = !showCursor;
      }, 530);
      
      return () => {
        if (timeoutId) {
          clearTimeout(timeoutId);
        }
        clearInterval(cursorInterval);
      };
    }
  });
</script>

<span class="typewriter">
  {displayText}
  {#if cursor && (isTyping || showCursor)}
    <span class="cursor">{cursorChar}</span>
  {/if}
</span>

<style>
  .typewriter {
    font-family: 'Courier New', monospace;
    white-space: pre-wrap;
  }

  .cursor {
    animation: blink 1.06s infinite;
    color: currentColor;
  }

  @keyframes blink {
    0%, 50% {
      opacity: 1;
    }
    51%, 100% {
      opacity: 0;
    }
  }
</style>
